import React from 'react';
import { Button, Icon, Row, Col, message } from 'antd';
import './singleFile.less';
import services from 'src/services/api';
import storage from '../../utils/storage';
import * as componentEvent from '../../utils/event/componentEvent';
const event = window.top.componentEvent || componentEvent;
const path = require('path');

class BigFile extends React.Component {
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      // console.log(nextProps);
      return {
        ...(nextProps.value || {}),
      };
    }
    return null;
  }
  constructor(props) {
    super(props);
    this.state = {
      filePath: '',
    };

    this.fileInputEl = React.createRef();
    this.urlInputEl = React.createRef();
    this.BYTES_PER_CHUNK = this.props.chunk || 1024 * 1024 * 2; //2M, 切块大小
    this.total = 0;
    this.start = 0;
    this.end = 0;
    this.index = 0;
    this.api = this.props.api || 'common';
    this.fileFormat = this.props.fileFormat || ['.pmml']; // 文件限制格式
  }

  componentDidMount() {}

  onFileChange = (e) => {
    this.total = 0;
    this.start = 0;
    this.end = 0;
    this.index = this.props.index || 0;
    const blob = e.currentTarget.files[0];
    if (!blob) return;
    const extname = path.extname(blob.name);
    // if (extname !== '.pmml') {
    //   message.warning('请导入格式为.pmml的文件');
    //   return;
    // }
    if (!this.fileFormat.includes(extname)) {
      message.warning(`请导入格式为${this.fileFormat.join('/')}的文件`);
      return;
    }
    // 如果大于500M
    if (blob.size / 1024 / 1024 > 500) {
      message.warning('请导入小于500M的文件');
      return;
    }
    this.total = Math.ceil(blob.size / this.BYTES_PER_CHUNK);
    const key = new Date().getTime();
    const userId = storage.userInfo.id;
    if (this.total > 1) {
      // while (this.start < blob.size) {
      //   this.end = this.start + this.BYTES_PER_CHUNK;
      //   if (this.end > blob.size) {
      //     this.end = blob.size;
      //   }
      //   this.uploadChunkFile(blob, this.index, this.start, this.end);
      //   this.start = this.end;
      //   this.index++;
      //   if (this.index >= this.total) {
      //     console.log('全部请求已发送');
      //   }
      // }
      event && event.eventEmitter.emit(event.SHOW_LOADING);
      this.uploadChunkFile(blob, key, userId);
    } else {
      this.uploadFile(blob, key, userId);
    }
  };

  uploadChunkFile(blob, key, userId) {
    this.end = this.start + this.BYTES_PER_CHUNK;
    if (this.end > blob.size) {
      this.end = blob.size;
    }
    const formData = new FormData();
    formData.append('scene', 'model');
    formData.append('file', blob.slice(this.start, this.end));
    formData.append('chunks', this.total);
    formData.append('chunk', this.index);
    formData.append('id', key + '_' + userId + '_' + blob.name);
    formData.append('name', blob.name);
    formData.append('type', blob.type);
    services[this.api].upload(formData).then((res) => {
      if (res.code === 200003) {
        console.log('未上传完继续');
        this.index += 1;
        this.start = this.end;
        if (this.index > this.total) {
          event && event.eventEmitter.emit(event.HIDE_LOADING);
          return message.error('上传片数溢出，上传失败')
        }
        this.uploadChunkFile(blob, key, userId);
      } else if (res.code === 0) {
        event && event.eventEmitter.emit(event.HIDE_LOADING);
        this.inputHandleChange(res.data.file_path);
      } else {
        event && event.eventEmitter.emit(event.HIDE_LOADING);
        message.warn(res.msg);
      }
    });
  }

  uploadFile(blob, key, userId) {
    const formData = new FormData();
    formData.append('scene', 'model');
    formData.append('file', blob);
    formData.append('chunks', 1);
    formData.append('chunk', 1);
    formData.append('id', key + '_' + userId + '_' + blob.name);
    formData.append('name', blob.name);
    formData.append('type', blob.type);
    services[this.api].upload(formData).then((res) => {
      if (res.code === 0) {
        this.inputHandleChange(res.data.file_path);
      }
    });
  }

  inputHandleChange(value) {
    this.triggerChange(value);
  }

  triggerChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(Object.assign({}, { filePath: changedValue }, changedValue));
    }
  };

  remove = () => {
    this.triggerChange('');
    this.fileInputEl.current.value = '';
  };

  render() {
    return (
      <div className='file-upload'>
        <Row type='flex' gutter={10}>
          <Col>
            <Button
              onClick={(e) => {
                this.fileInputEl.current.click();
                e.target.blur();
              }}
            >
              选择文件
            </Button>
          </Col>
          <Col>
            {this.state.filePath && (
              <div>
                {this.state.filePath}
                <Icon
                  type='close-circle'
                  style={{ cursor: 'pointer', color: '#006eff', marginLeft: '10px' }}
                  onClick={this.remove}
                />
              </div>
            )}
          </Col>
        </Row>

        <input name='file' hidden type='file' ref={this.fileInputEl} onInput={this.onFileChange} />
        <input ref={this.urlInputEl} name='text' hidden type='text' />
      </div>
    );
  }
}

export default BigFile;
